﻿using MediatR;
using SupplyChain.Domain.Entities;
using SupplyChain.Infrastructure.Interface;
using SupplyChain.Write.API.Application.Command.PurchaseOrder;

namespace SupplyChain.Write.API.Application.CommandHandler.PurchaseOrder
{
    public class GetPurchaseOrderListHandler : IRequestHandler<GetPurchaseOrderListCommand, List<Domain.Entities.PurchaseOrder>>
    {
        private readonly IBaseRepository<Domain.Entities.PurchaseOrder> repository;
        private readonly IBaseRepository<PurchaseOrderDetail> detailRep;

        public GetPurchaseOrderListHandler(IBaseRepository<Domain.Entities.PurchaseOrder> repository,
                                           IBaseRepository<PurchaseOrderDetail> detailRep)
        {
            this.repository = repository;
            this.detailRep = detailRep;
        }

        public async Task<List<Domain.Entities.PurchaseOrder>> Handle(GetPurchaseOrderListCommand request, CancellationToken cancellationToken)
        {
            List<Domain.Entities.PurchaseOrder> orders = await repository.GetByWhereAsync(x => !x.IsDel);
            List<PurchaseOrderDetail> details = await detailRep.GetByWhereAsync(x => !x.IsDel);
            foreach (Domain.Entities.PurchaseOrder item in orders)
            {
                item.Details = details.Where(x => x.PuId.Equals(item.Id)).ToList();
            }
            return await Task.FromResult(orders);
        }
    }
}
